import axios, {AxiosInstance, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig} from 'axios'
import config from '@/static/config'
import {message} from 'antd'
interface CodeType <T> {
  message: string
  code: number
  data: T
}
class Http {
  private install:AxiosInstance
  constructor(config: AxiosRequestConfig) {
    this.install = axios.create(config)
    this.interceptor()
  }
  private interceptor (): void {
    // 请求拦截器
    this.install.interceptors.request.use((config:InternalAxiosRequestConfig): InternalAxiosRequestConfig => {
      const token:string = sessionStorage.getItem("token") as string
      if (token) {
        config.headers!["token"] = token
      }
      return config
    }, (error) => {
      return error
    })
    // 响应拦截器
    this.install.interceptors.response.use((config:AxiosResponse<CodeType<unknown>>):AxiosResponse["data"] => {
      if (config.status === 500 && config.data.message === 'token 失效'){
        sessionStorage.clear()
        window.location.reload()
      }
      if (config.data.code !== 200) {
        console.log(config)
        message.error(config.data.message)
      }
      return config.data
    }, error => {
      if (error.response.data.message.includes("token")) {
        sessionStorage.clear()
        window.location.reload()
      }
      return error
    })
  }
  public get<T = string> (url: string, params?: AxiosRequestConfig["params"]):Promise<CodeType<T>> {
    return this.install.request({
      url,
      method: 'get',
      params
    })
  }
  public post<T = string> (url: string, data: AxiosRequestConfig["data"]):Promise<CodeType<T>> {
    return this.install.request({
      url,
      method: 'post',
      data
    })
  }
  public put<T = string> (url: string, data?: AxiosRequestConfig["data"]):Promise<CodeType<T>> {
    return this.install.request({
      url,
      method: 'put',
      data
    })
  }
  public del<T = string> (url: string, params:AxiosRequestConfig["params"]):Promise<CodeType<T>> {
    return this.install.request({
      url,
      method: 'delete',
      params
    })
  }
}


const http = new Http({
  baseURL: config.url + "sms/"
})


export default http
